<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <img src="../images/2.jpg" width="200" alt="">
</body>
<script>
    // canvas
    function convertImgToBase64(url, callback) {
        let canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            img = new Image();
        img.crossOrigin = 'anonymous';//解决Canvas.toDataURL 图片跨域问题
        img.onload = () => {
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); // 获取到图片的格式
            let dataURL = canvas.toDataURL("image/" + ext); // 得到base64 编码的 dataURL
            callback && callback(dataURL);
            canvas = null;
        };
        img.src = url;
    }

    var baseUrl = ''
    convertImgToBase64("../images/2.jpg", (baseUrl) => {
        // baseUrl = baseUrl
        // var img = document.createElement("img");
        var img = new Image(200);
        img.src = baseUrl;

        document.body.appendChild(img);
    })

</script>

</html>